<template>
  <div class="min-h-screen bg-gray-50 p-4 md:p-6 lg:p-8">
    <div class="max-w-4xl mx-auto">
      <a-card title="图片转Base64" class="mb-4">
        <div class="space-y-4">
          <!-- 图片上传 -->
          <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center">
            <input
              type="file"
              accept="image/*"
              class="hidden"
              ref="fileInput"
              @change="handleImageUpload"
            />
            <div v-if="!imageUrl" @click="triggerFileInput" class="cursor-pointer">
              <upload-outlined class="text-4xl text-gray-400" />
              <p class="mt-2 text-sm text-gray-500">点击或拖拽图片到此处</p>
            </div>
            <img v-else :src="imageUrl" class="max-h-64 mx-auto" />
          </div>

          <!-- Base64输出 -->
          <div v-if="base64String" class="space-y-4">
            <div class="flex justify-between items-center">
              <span class="text-sm font-medium text-gray-700">Base64编码</span>
              <a-button size="small" @click="copyToClipboard">复制</a-button>
            </div>
            <a-textarea
              v-model:value="base64String"
              :rows="6"
              readonly
              class="font-mono text-sm"
            />
            <div class="flex justify-between">
              <span class="text-sm text-gray-500">
                文件大小: {{ formatFileSize(fileSize) }}
              </span>
              <a-button type="primary" @click="resetImage">重置</a-button>
            </div>
          </div>
        </div>
      </a-card>

      <!-- 使用说明 -->
      <a-card title="使用说明" class="mb-4">
        <ol class="list-decimal list-inside space-y-2 text-gray-600">
          <li>支持常见图片格式：PNG、JPG、GIF等</li>
          <li>生成的Base64可直接用于img标签的src属性</li>
          <li>建议图片大小不超过1MB，否则Base64字符串会很长</li>
          <li>Base64编码会使文件大小增加约33%</li>
        </ol>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'

const fileInput = ref<HTMLInputElement | null>(null)
const imageUrl = ref('')
const base64String = ref('')
const fileSize = ref(0)

const triggerFileInput = () => {
  fileInput.value?.click()
}

const handleImageUpload = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.files && target.files[0]) {
    const file = target.files[0]
    if (!file.type.startsWith('image/')) {
      message.error('请上传图片文件')
      return
    }

    fileSize.value = file.size

    const reader = new FileReader()
    reader.onload = (e) => {
      if (e.target?.result) {
        imageUrl.value = e.target.result as string
        base64String.value = e.target.result as string
      }
    }
    reader.readAsDataURL(file)
  }
}

const copyToClipboard = async () => {
  try {
    await navigator.clipboard.writeText(base64String.value)
    message.success('已复制到剪贴板')
  } catch (err) {
    message.error('复制失败')
  }
}

const resetImage = () => {
  imageUrl.value = ''
  base64String.value = ''
  fileSize.value = 0
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
</script> 